var tname = "";
function getById(id){
	return document.getElementById(id);
}
// 验证注册账号
function check_account(account){
	var pattern = new RegExp(/^[a-zA-Z]{2}[0-9]{6}.*$/);  	
	var isaccount = pattern.exec(account);
	if(isaccount!=null){
		return "true";	
	}else{
		return "false";					
	}
}
// 验证邮箱
function check_email(email){
	var pattern = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);  	
	var isemail = pattern.exec(email);
	if(isemail!=null){
		return "true";	
	}else{
		return "false";					
	}
}
// 验证手机号
function check_mobile(phone){
	var pattern = new RegExp(/^[1]([3-8][0-9]{1}|59|58|88|89)[0-9]{8}$/); 
	var isemail = pattern.exec(phone);
	if(isemail!=null){
		return true;	
	}else{
		return false;					
	}
}
// 验证多个号码(多个号码用","分隔,有手机号和固话)
function check_phone(phone){
	var pattern = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
	var regu = /^[1]([3-8][0-9]{1}|59|58|88|89)[0-9]{8}$/;
	var phoneList = phone.split(",");
	for(var i=0;i<phoneList.length;i++){
		var phonevalue=phoneList[i];
		if(phonevalue!=""){
			var istel = pattern.exec(phonevalue);
			var isphone = regu.exec(phonevalue);
			if(istel!=null||isphone!=null){
				continue;
			}else{
				return phonevalue;					
			}			
		}
	}
	return "true";
}

// 验证身份证
function IdentityCodeValid(code) { 
    var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
    var tip = "";
    var pass= "true";
    
    if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
        tip = "身份证号格式错误";
        pass = "false";
    }
    
   else if(!city[code.substr(0,2)]){
        tip = "地址编码错误";
        pass = "false";
    }
    else{
        // 18位身份证需要验证最后一位校验位
        if(code.length == 18){
            code = code.split('');
            // ∑(ai×Wi)(mod 11)
            // 加权因子
            var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
            // 校验位
            var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++)
            {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            if(parity[sum % 11] != code[17]){
                tip = "校验位错误";
                pass ="false";
            }
        }
    }
    // if(!pass) alert(tip);
    return pass;
}



function isnull(obj) {
	if (undefined == obj || null == obj || "" == obj) {
		return true;
	}
	return false;
}
// add by funny at 2011/11/21
String.prototype.trim = function () {
	return this.replace(/(^\s*)|(\s*$)/g, "");
};
function ajaxUrl(url)
{
	var cUrl=url;
	if(url.indexOf("?")!=-1)
	{
		cUrl+="&dt="+new Date().getTime();
	}
	else 
		cUrl+="?dt="+new Date().getTime();
	return cUrl;
}
function isNum(str)
{
	if(!/^-?\d+(\.\d+)?$/.test(str))
	{
		return false;
	}
	return true;
}

//验证零和非零开头的数字
function isNum1(str)
{
	if(!/^(0|[1-9][0-9]*)$/.test(str))
	{
		return false;
	}
	return true;
}

function onMouseoverAutoClear(obj,str){
	if(""==obj.value||obj.value==str){
		obj.value="";
		tname=str;
		obj.focus();
	}
}
function onMouseexit(obj){
	if(""==obj.value){
		// obj.className="txtc1";
		obj.value=tname;
	}
}

// end funny

// 获取单选框值
function getByRValue(name){
	var obj=document.getElementsByName(name);	
	for(var i=0;i<obj.length;i++){
		if(obj[i].checked){
			return obj[i].value;
		}
	}
	return null;
}
// 获取复选框值
function getByCValue(name){
	var check=document.getElementsByName(name);
	var arr=new Array();
	var j=0;
	for(var i=0;i<check.length;i++){
		if(check[i].checked==true){
			arr[j]=check[i].value;
			j++;
		}
	}
	return arr;
}

// 其他实际应用：
// 可以根据需要，配合以下方法实现自己要实现的功能；
var hostname = location.hostname; // 获取当前域名(不包含http://)
var localurl = location.href;   // 获取当前完整的URL地址信息(包含http://，域名，路径，具体文件和全部传递参数)
var referurl = document.referrer; // 获取上一页完整的URL信息(包含http://，域名，路径，具体文件和全部传递参数)
// javascript获取指定参数及其对应的值
function getParameter(paraStr, url){   
  var result = "";   
  // 获取URL中全部参数列表数据
  var str = "&" + url.split("?")[1];   
  var paraName = paraStr + "=";   
  // 判断要获取的参数是否存在
  if(str.indexOf("&"+paraName)!=-1)   
  {   
      // 如果要获取的参数到结尾是否还包含“&”
      if(str.substring(str.indexOf(paraName),str.length).indexOf("&")!=-1)   
      {   
          // 得到要获取的参数到结尾的字符串
          var TmpStr=str.substring(str.indexOf(paraName),str.length);   
          // 截取从参数开始到最近的“&”出现位置间的字符
          result=TmpStr.substr(TmpStr.indexOf(paraName),TmpStr.indexOf("&")-TmpStr.indexOf(paraName));     
      }   
      else   
      {     
          result=str.substring(str.indexOf(paraName),str.length);     
      }   
  }     
  else   
  {     
      result="无此参数";     
  }     
  return (result.replace("&",""));     
}   

function getlocalUrl(para){
// 调用方法：var 变量名 = getParameter("要获取的参数名", URL地址)
var r = getParameter(para,localurl);   
// 根据得到的结果可以使用
// var pName = r.split("=")[0]; //获取参数名
var pValue = r.split("=")[1]; // 获取参数值
	return pValue;	
}

/** 货币格式化函数 * */
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-')  + num + '.' + cents);
}
/** 还原货币格式化函数 * */
function restoreFormatCurrency(num){
       var num1=num.replace(',','').replace(/,/g,''); 
    return num1;
}
// 加载显示分页选择页数按钮(当前页数,每页显示条数,总页数,总记录数,加载层的id,执行方法,前置参数,后置参数)
function toLoadPage(page, page_size, page_count, count, id,md,fmd,lmd) {
	if(isnull(fmd)){fmd="(";}else{fmd="("+fmd+",";}
	if(isnull(lmd)){lmd=");";}else{lmd+=");";}
	var t = "<span>";
	if (page <= 1) {
		t += "当前第　1　页</span>";
	} else {
		t += "<a href='javascript:void(0);' onclick='"
				+ md +fmd+"1"+lmd
				+"'>首页</a></span><span><a href='javascript:void(0);' onclick='"
				+ md + fmd+(page - 1)+ lmd
				+"'>上一页</a></span><span>当前第　" + page + "　页</span>";
	}
	if ((page + 1) <= page_count) {
		t += "<span><a href='javascript:void(0);' onclick='"
				+ md + fmd + (page + 1)	+ lmd
				+"'>下一页</a></span><span><a href='javascript:void(0);' onclick='"
				+ md + fmd+ page_count +lmd
				+"'>尾页</a></span>";
	} else {
		t += "";
	}
	if(!isnull(page_count)){
		t += "<span>共" + page_count + "页</span";
	}
	if(!isnull(count)){
		t += "<span>共" + count + "条数据</span>";		
	}
// alert(t);
	$("#" + id).html(t);
	}

function exeAjax(url,fun,data,errfun,type,dataType,contentType){
	if(undefined==data||null==data){data={};};
	if(undefined==type||null==type){type='post';};
	if(undefined==dataType||null==dataType){dataType='json';};
	if(undefined==contentType||null==contentType){contentType='application/x-www-form-urlencoded; charset=utf-8';};
	var errfun=null;
	if(undefined==errfun||null==errfun){errfun=function() {	};};// alert("服务器连接超时");};};
	$.ajax({
		url : url,
		data : data,
		type : type,
		dataType : dataType,
		contentType : contentType,
		success : fun,
		error : errfun
	});
}

var HomepageFavorite = {
// 设为首页
Homepage: function () {
	if (document.all) {
    	document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage(window.location.href);
	}else if (window.sidebar) {
    	if (window.netscape) {
        	try {
            	netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }catch (e) {
            	alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true");
                history.go(-1);
            }
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage', window.location.href);
}},
// 加入收获
Favorite: function Favorite(sURL, sTitle) {
	try {
		window.external.addFavorite(sURL, sTitle);
	}catch (e) {
		try {
			window.sidebar.addPanel(sTitle, sURL, "");
		}catch (e) {
			alert("加入收藏失败,请手动添加.");
}}}};

// 复制到粘贴板
function copyToClipboard(txt) {   
if(window.clipboardData) {   
window.clipboardData.clearData();   
window.clipboardData.setData("Text", txt);   
} else if(navigator.userAgent.indexOf("Opera") != -1) {   
window.location = txt;   
 } else if (window.netscape) {   
try {   
 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");   
} catch (e) {   
   alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");   
  }   
  var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);   
  if (!clip)   
       return;   
  var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);   
  if (!trans)   
       return;   
  trans.addDataFlavor('text/unicode');   
  var str = new Object();   
  var len = new Object();   
  var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);   
  var copytext = txt;   
  str.data = copytext;   
  trans.setTransferData("text/unicode",str,copytext.length*2);   
  var clipid = Components.interfaces.nsIClipboard;   
  if (!clip)   
   return false;   
  clip.setData(trans,null,clipid.kGlobalClipboard); 
 }
}  



// 从一个给定的数组arr中,随机返回num个不重复项
function getArrayItems(arr, num) {
	// 新建一个数组,将传入的数组复制过来,用于运算,而不要直接操作传入的数组;
	var temp_array = new Array();
	for ( var index in arr) {
		temp_array.push(arr[index]);
	}
	// 取出的数值项,保存在此数组
	var return_array = new Array();
	for ( var i = 0; i < num; i++) {
		// 判断如果数组还有可以取出的元素,以防下标越界
		if (temp_array.length > 0) {
			// 在数组中产生一个随机索引
			var arrIndex = Math.floor(Math.random() * temp_array.length);
			// 将此随机索引的对应的数组元素值复制出来
			return_array[i] = temp_array[arrIndex];
			// 然后删掉此索引的数组元素,这时候temp_array变为新的数组
			temp_array.splice(arrIndex, 1);
		} else {
			// 数组中数据项取完后,退出循环,比如数组本来只有10项,但要求取出20项.
			break;
		}
	}
	return return_array;
}
